package cn.wen233.iocdemo.infrustructure.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

/**
 * 信道
 *
 * @author wenei
 * @date 2021-06-22 9:25
 */
public class TcpChannel {

    private static final Logger log = LoggerFactory.getLogger(TcpChannel.class);

    public static void send(String ip, int port, String message) {
        InetAddress ipAddress = null;
        try {
            ipAddress = InetAddress.getByName(ip);
            Socket socket = new Socket(ipAddress, port);
            try (OutputStream outputStream = socket.getOutputStream()) {
                outputStream.write(message.getBytes(StandardCharsets.UTF_8));
                outputStream.flush();
            }
            socket.close();
        } catch (UnknownHostException e) {
            log.warn("主机{}解析错误", ip);
            e.printStackTrace();
        } catch (IOException e) {
            log.warn("网络io读取异常");
            e.printStackTrace();
        }

    }
}
